﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Mvc.ModelBinders;
using MvcEngine.Gallery.Models;
using MvcEngine.Core.Extensions;
using MvcEngine.Core;
using System.Web;
using System.Web.Mvc;
using MvcEngine.Core.Common.Slugs;

namespace MvcEngine.Gallery.ModelBinders
{
    public class GalleryCategoryModelBinder : ModelBinderBase
    {
        public override object Bind(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            HttpRequestBase request = controllerContext.HttpContext.Request;
            GalleryCategory category = IoC.Resolve<GalleryCategory>();

            category.Name = request.Form.Get("Name");
            category.OrderNumber = request.Form.Get("OrderNumber").ToInt();
            category.Slug = request.Form.Get("Slug");
            category.Description = request.Form.Get("Description");
            category.Keywords = request.Form.Get("Keywords");
            category.Visible = request.Form.Get("Visible").Contains("true");

            if (string.IsNullOrEmpty(category.Slug) && !string.IsNullOrEmpty(category.Name)) 
                category.Slug = controllerContext.HttpContext.Server.HtmlEncode(IoC.Resolve<ISlugConverter>().Convert(category.Name));

            Validate(category, controllerContext);
            return category;
        }
    }
}
